package cn.sitcat.springbootshiro.controller;

import cn.sitcat.springbootshiro.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;


/**
 * @author hiseico
 * @date 2019/4/13 17:40
 * @desc
 */
@Controller
public class HelloController {

    @RequestMapping("/test")
    public String hello(Model model) {
        model.addAttribute("msg", "springboot project created success !");
        return "success";
    }

    @RequestMapping("/add")
    public String add() {
        return "user/add";
    }

    @RequestMapping("/update")
    public String update() {
        return "user/update";
    }

    @RequestMapping("noAuth")
    public String noAuth(Model model) {
        model.addAttribute("msg", "无权限！");
        return "noAuth";
    }

    /**
     * 登录操作
     *
     * @param name
     * @param password
     * @param model
     * @return
     */
    @RequestMapping("/login")
    public String login(String name, String password, Model model) {
        /**
         * 使用shiro编写认证的操作
         */
        //1.获取Subject
        Subject subject = SecurityUtils.getSubject();
        //2.封装用户数据
        UsernamePasswordToken token = new UsernamePasswordToken(name, password);
        try {
//3.执行登录方法
            subject.login(token);

        } catch (UnknownAccountException e) {
            //登录失败，用户名错误
            model.addAttribute("msg", "用户名不存在！");
            return "login";
        } catch (IncorrectCredentialsException e) {
            //登录失败，密码错误
            model.addAttribute("msg", "用户名或密码错误！");
            return "login";
        }
        return "redirect:/test";
    }
}
